----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date:    21:19:54 01/29/2009 
-- Design Name: 
-- Module Name:    generate_48k_clk - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: 
--
-- !warning! 
--	clock is not buffered inside this module, and needs to be
-- routed through a clock buffer at the top level, due to partial
-- reconfiguration constraints 
-- !warning!
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity generate_48k_clk is
    Port ( AC97_Bit_Clk : in  STD_LOGIC;
           reset 			: in  STD_LOGIC;
			  sync			: in 	std_logic;
           clk_48k		: out  STD_LOGIC;
			  locked_48k	: out std_logic;
			  status			: out std_logic);
end generate_48k_clk;

architecture Behavioral of generate_48k_clk is
	signal 	counter	: integer range 0 to 255 := 0;
	signal 	start		: std_logic := '0';
	signal clk_48k_i	: std_logic := '0';
begin
	--unbuffered
	clk_48k <= clk_48k_i;
	
	process(AC97_Bit_Clk, reset)
	begin
		if reset = '0' then
			counter <= 0;
			start <= '0';
			locked_48k <= '0';
		elsif AC97_Bit_Clk'event and AC97_Bit_Clk = '1' then
			if start = '1' then
				if counter = 0 then
					--if sync = '0' then
					--	status <= '0';			--out of sync
					--end if;
					clk_48k_i <= '1';
					counter <= counter + 1;
				elsif counter = 255 then
					counter <= 0;
					locked_48k <= '1';	--cycle complete, clock locked
				elsif counter = 128 then
					counter <= counter + 1;
					clk_48k_i <= '0';
				else
					counter <= counter + 1;
				end if;
			elsif sync = '1' then
				start <= '1';				--start clock
				clk_48k_i <= '1';			--setup clock
				counter <= 1;				--first cycle dealt with
				status <= '1';				--status = '1' => OK
				locked_48k <= '0';
			end if;
		end if;
	end process;
end Behavioral;
